package cn.wang.service.impl;

import cn.wang.common.Exceptions.impl.LyException;
import cn.wang.common.enums.impl.ExceptionEnum;
import cn.wang.service.IUploadService;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
@Slf4j
public class UploadServiceImpl implements IUploadService {
    @Value("${ly.service.upload.baseUrl}")
    String baseUrl; // 保存图片的域名
    @Value("#{'${ly.service.upload.allowImageType}'.split(',')}")
    List<String> AllowImageType;    // 允许上传的图片类型
    @Autowired
    private FastFileStorageClient storageClient;

    @Override
    public String uploadImage(MultipartFile file) {

        // 对文件进行校验, 验证是否为图片
        try {
            // ImageIO.read读取非文件类型的文件返回的结果为null
            BufferedImage imageInput = ImageIO.read(file.getInputStream());
            // 如果imageInput为null就表示上传的文件类型不是图片
            if (imageInput==null){
                throw new LyException(ExceptionEnum.FILE_NOT_IS_IMAGE);
            }
            // 如果图片的类型不是允许的图片类型也会报错
            if ( !AllowImageType.contains(file.getContentType())){
                throw new LyException(ExceptionEnum.IMAGE_NOT_ALLOW);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            // 保存文件
            String filename = file.getOriginalFilename();
            String suffix = StringUtils.substringAfterLast(filename, ".");
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), suffix, null);
            // 返回保存后的文件地址
            return baseUrl+storePath.getFullPath();
        } catch (IOException e) {
            log.error("上传文件失败"+e);
            throw new LyException(ExceptionEnum.UPLOAD_IMAGE_FAILED);
        }
    }
}
